<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <div class="welcome-section">
        <h1 class="welcome-title">欢迎回来，{{ userName }}</h1>
        <div class="current-time">{{ currentDateTime }}</div>
      </div>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-refresh" circle @click="refreshData"></el-button>
      </div>
    </div>

    <!-- KPI Cards Section -->
    <el-row :gutter="20" class="dashboard-cards">
      <el-col :xs="24" :sm="12" :md="6" v-for="(card, index) in statCards" :key="index">
        <el-card shadow="hover" :body-style="{ padding: '20px' }" class="stat-card" :class="card.type">
          <div class="card-content">
            <div class="card-icon-container">
              <i :class="card.icon"></i>
            </div>
            <div class="card-data">
              <div class="card-value">{{ card.value }}</div>
              <div class="card-title">{{ card.title }}</div>
              <div class="card-change" :class="card.changeType">
                <i :class="card.changeType === 'increase' ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ card.changeValue }}% 较上月
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Charts Section -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :md="16">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span class="chart-title">销售趋势分析</span>
            <div class="chart-actions">
              <el-radio-group v-model="salesChartPeriod" size="mini">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">全年</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-container" ref="salesTrend"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="8">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span class="chart-title">商品品类分布</span>
            <el-dropdown trigger="click" @command="handleCategoryCommand">
              <span class="el-dropdown-link">
                筛选 <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="all">全部品类</el-dropdown-item>
                <el-dropdown-item command="main">主要品类</el-dropdown-item>
                <el-dropdown-item command="growing">增长最快</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="chart-container" ref="categoryPie"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Additional Insights Row -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span class="chart-title">热销商品排行</span>
            <el-tooltip content="显示最热销的前10个商品" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </div>
          <el-table :data="hotProducts" style="width: 100%" :show-header="false">
            <el-table-column width="50">
              <template slot-scope="scope">
                <div class="rank-circle" :class="scope.$index < 3 ? 'top-rank' : ''">
                  {{ scope.$index + 1 }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称">
              <template slot-scope="scope">
                <div class="product-info">
                  <span class="product-name">{{ scope.row.name }}</span>
                  <span class="product-category">{{ scope.row.category }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="sales" label="销量" width="120" align="right">
              <template slot-scope="scope">
                <span class="sales-value">{{ scope.row.sales }}</span>
                <el-progress 
                  :percentage="(scope.row.sales / hotProducts[0].sales) * 100" 
                  :show-text="false" 
                  :stroke-width="4"
                  :color="scope.$index < 3 ? '#409EFF' : '#909399'"
                ></el-progress>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span class="chart-title">渠道转化分析</span>
            <div class="date-selector">
              <el-date-picker
                v-model="channelDateRange"
                type="daterange"
                size="mini"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </div>
          <div class="chart-container" ref="channelConversion"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Latest Activity and Tasks -->
    <el-row :gutter="20" class="activity-row">
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" class="activity-card">
          <div slot="header" class="activity-header">
            <span class="activity-title">最新活动</span>
            <el-button type="text" @click="viewAllActivities">查看全部</el-button>
          </div>
          <div class="activity-timeline">
            <el-timeline>
              <el-timeline-item
                v-for="(activity, index) in recentActivities"
                :key="index"
                :type="activity.type"
                :color="activity.color"
                :timestamp="activity.time"
                :size="activity.important ? 'large' : 'normal'"
              >
                <div class="timeline-content">
                  <div class="timeline-title">{{ activity.title }}</div>
                  <div class="timeline-desc">{{ activity.description }}</div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" class="task-card">
          <div slot="header" class="task-header">
            <span class="task-title">待办事项</span>
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="addNewTask">新增</el-button>
          </div>
          <div class="task-list">
            <el-checkbox-group v-model="completedTasks">
              <div v-for="(task, index) in pendingTasks" :key="index" class="task-item">
                <el-checkbox :label="task.id">
                  <span :class="{ 'task-completed': completedTasks.includes(task.id) }">{{ task.content }}</span>
                </el-checkbox>
                <div class="task-meta">
                  <el-tag size="mini" :type="task.priority">{{ task.priorityLabel }}</el-tag>
                  <span class="task-date">{{ task.deadline }}</span>
                </div>
              </div>
            </el-checkbox-group>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'Dashboard',
  data() {
    return {
      userName: '管理员',
      currentDateTime: '',
      salesChartPeriod: 'month',
      completedTasks: [],
      channelDateRange: [new Date(new Date().setDate(new Date().getDate() - 30)), new Date()],
      
      // KPI Cards Data
      statCards: [
        {
          title: '总销售额',
          value: '¥126,560',
          icon: 'el-icon-s-goods',
          type: 'primary',
          changeType: 'increase',
          changeValue: '12.5'
        },
        {
          title: '订单总量',
          value: '1,284',
          icon: 'el-icon-s-order',
          type: 'success',
          changeType: 'increase',
          changeValue: '8.2'
        },
        {
          title: '新增用户',
          value: '256',
          icon: 'el-icon-user-solid',
          type: 'info',
          changeType: 'increase',
          changeValue: '5.6'
        },
        {
          title: '商品总数',
          value: '856',
          icon: 'el-icon-s-shop',
          type: 'warning',
          changeType: 'decrease',
          changeValue: '2.3'
        }
      ],
      
      // Hot Products Data
      hotProducts: [
        { name: '优质黑糯玉米', category: '蔬菜类', sales: 1253 },
        { name: '红心火龙果', category: '水果类', sales: 1100 },
        { name: '有机生菜', category: '蔬菜类', sales: 954 },
        { name: '特级大米', category: '粮食类', sales: 830 },
        { name: '山竹', category: '水果类', sales: 756 },
        { name: '新鲜鸡蛋', category: '生鲜类', sales: 692 },
        { name: '牛油果', category: '水果类', sales: 621 },
        { name: '有机胡萝卜', category: '蔬菜类', sales: 597 },
        { name: '豆腐', category: '豆制品', sales: 542 },
        { name: '猪肉', category: '肉类', sales: 468 }
      ],
      
      // Activity Data
      recentActivities: [
        {
          title: '新品上架',
          description: '新增有机草莓系列产品，共8个SKU',
          time: '今天 14:35',
          type: 'primary',
          color: '#409EFF',
          important: true
        },
        {
          title: '促销活动',
          description: '水果类商品限时8折促销活动已开始',
          time: '今天 09:20',
          type: 'success',
          color: '#67C23A',
          important: false
        },
        {
          title: '系统更新',
          description: '系统已完成订单管理模块升级',
          time: '昨天 16:45',
          type: 'info',
          color: '#909399',
          important: false
        },
        {
          title: '库存预警',
          description: '3个SKU库存不足，请及时补货',
          time: '昨天 10:12',
          type: 'warning',
          color: '#E6A23C',
          important: true
        },
        {
          title: '用户反馈',
          description: '收到5条用户关于配送时间的反馈',
          time: '前天 08:30',
          type: 'danger',
          color: '#F56C6C',
          important: false
        }
      ],
      
      // Task Data
      pendingTasks: [
        { id: 1, content: '完成本月销售报表', priority: 'danger', priorityLabel: '紧急', deadline: '今天' },
        { id: 2, content: '审核新入库商品信息', priority: 'warning', priorityLabel: '重要', deadline: '明天' },
        { id: 3, content: '召开团队周会', priority: 'primary', priorityLabel: '普通', deadline: '周三' },
        { id: 4, content: '更新商品促销策略', priority: 'success', priorityLabel: '进行中', deadline: '本周五' },
        { id: 5, content: '处理客户退款申请', priority: 'danger', priorityLabel: '紧急', deadline: '今天' }
      ],
      
      // Charts instances
      salesChart: null,
      categoryChart: null,
      channelChart: null
    }
  },
  mounted() {
    this.setCurrentTime()
    this.initCharts()
    
    // Update time each minute
    this.timeInterval = setInterval(this.setCurrentTime, 60000)
    
    // Resize charts when window resizes
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    // Clean up
    clearInterval(this.timeInterval)
    window.removeEventListener('resize', this.resizeCharts)
    
    if (this.salesChart) {
      this.salesChart.dispose()
    }
    if (this.categoryChart) {
      this.categoryChart.dispose()
    }
    if (this.channelChart) {
      this.channelChart.dispose()
    }
  },
  methods: {
    setCurrentTime() {
      const now = new Date()
      const options = { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric', 
        weekday: 'long', 
        hour: '2-digit', 
        minute: '2-digit'
      }
      this.currentDateTime = now.toLocaleDateString('zh-CN', options)
    },
    refreshData() {
      this.$message({
        message: '数据已刷新',
        type: 'success'
      })
      
      // Simulate data refresh by reinitializing charts
      this.initCharts()
    },
    initCharts() {
      this.$nextTick(() => {
        this.initSalesChart()
        this.initCategoryChart()
        this.initChannelChart()
      })
    },
    resizeCharts() {
      if (this.salesChart) {
        this.salesChart.resize()
      }
      if (this.categoryChart) {
        this.categoryChart.resize()
      }
      if (this.channelChart) {
        this.channelChart.resize()
      }
    },
    initSalesChart() {
      const chartDom = this.$refs.salesTrend
      if (!chartDom) return
      
      this.salesChart = echarts.init(chartDom)
      
      // Sample data - would normally come from an API
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        legend: {
          data: ['线上订单', '门店订单', '总计']
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '线上订单',
            type: 'bar',
            stack: 'total',
            barWidth: '60%',
            emphasis: {
              focus: 'series'
            },
            data: [320, 302, 301, 334, 390, 330, 320, 334, 350, 370, 390, 420]
          },
          {
            name: '门店订单',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330]
          },
          {
            name: '总计',
            type: 'line',
            emphasis: {
              focus: 'series'
            },
            data: [440, 434, 402, 468, 480, 560, 530, 516, 541, 604, 680, 750]
          }
        ],
        color: ['#409EFF', '#67C23A', '#E6A23C']
      }
      
      this.salesChart.setOption(option)
    },
    initCategoryChart() {
      const chartDom = this.$refs.categoryPie
      if (!chartDom) return
      
      this.categoryChart = echarts.init(chartDom)
      
      // Sample data
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: ['蔬菜类', '水果类', '肉类', '粮食类', '豆制品', '其他']
        },
        series: [
          {
            name: '品类销售',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 1048, name: '蔬菜类' },
              { value: 735, name: '水果类' },
              { value: 580, name: '肉类' },
              { value: 484, name: '粮食类' },
              { value: 300, name: '豆制品' },
              { value: 200, name: '其他' }
            ]
          }
        ],
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#DCDFE6']
      }
      
      this.categoryChart.setOption(option)
    },
    initChannelChart() {
      const chartDom = this.$refs.channelConversion
      if (!chartDom) return
      
      this.channelChart = echarts.init(chartDom)
      
      // Sample data for funnel chart
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c}%'
        },
        legend: {
          data: ['访问', '咨询', '加购', '下单', '支付', '复购']
        },
        series: [
          {
            name: '转化率',
            type: 'funnel',
            left: '10%',
            top: 60,
            bottom: 60,
            width: '80%',
            min: 0,
            max: 100,
            minSize: '0%',
            maxSize: '100%',
            sort: 'descending',
            gap: 2,
            label: {
              show: true,
              position: 'inside'
            },
            labelLine: {
              length: 10,
              lineStyle: {
                width: 1,
                type: 'solid'
              }
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 1
            },
            emphasis: {
              label: {
                fontSize: 20
              }
            },
            data: [
              { value: 100, name: '访问' },
              { value: 80, name: '咨询' },
              { value: 60, name: '加购' },
              { value: 40, name: '下单' },
              { value: 30, name: '支付' },
              { value: 20, name: '复购' }
            ]
          }
        ],
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#DCDFE6']
      }
      
      this.channelChart.setOption(option)
    },
    handleCategoryCommand(command) {
      this.$message({
        message: `已切换到${command === 'all' ? '全部品类' : command === 'main' ? '主要品类' : '增长最快品类'}视图`,
        type: 'success'
      })
    },
    viewAllActivities() {
      this.$message({
        message: '正在跳转到所有活动页面',
        type: 'info'
      })
    },
    addNewTask() {
      this.$prompt('请输入任务内容', '新增任务', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '任务内容不能为空'
      }).then(({ value }) => {
        const newTask = {
          id: this.pendingTasks.length + 1,
          content: value,
          priority: 'primary',
          priorityLabel: '普通',
          deadline: '待定'
        }
        this.pendingTasks.unshift(newTask)
        this.$message({
          type: 'success',
          message: '任务已添加'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消添加'
        })
      })
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.welcome-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #303133;
}

.current-time {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.dashboard-cards {
  margin-bottom: 20px;
}

.stat-card {
  transition: all 0.3s;
  height: 100%;
  border-radius: 8px;
  position: relative;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

.stat-card.primary {
  border-top: 4px solid #409EFF;
}

.stat-card.success {
  border-top: 4px solid #67C23A;
}

.stat-card.info {
  border-top: 4px solid #909399;
}

.stat-card.warning {
  border-top: 4px solid #E6A23C;
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon-container {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.2), rgba(64, 158, 255, 0.1));
}

.stat-card.primary .card-icon-container {
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.2), rgba(64, 158, 255, 0.1));
}

.stat-card.success .card-icon-container {
  background: linear-gradient(135deg, rgba(103, 194, 58, 0.2), rgba(103, 194, 58, 0.1));
}

.stat-card.info .card-icon-container {
  background: linear-gradient(135deg, rgba(144, 147, 153, 0.2), rgba(144, 147, 153, 0.1));
}

.stat-card.warning .card-icon-container {
  background: linear-gradient(135deg, rgba(230, 162, 60, 0.2), rgba(230, 162, 60, 0.1));
}

.card-icon-container i {
  font-size: 28px;
}

.stat-card.primary .card-icon-container i {
  color: #409EFF;
}

.stat-card.success .card-icon-container i {
  color: #67C23A;
}

.stat-card.info .card-icon-container i {
  color: #909399;
}

.stat-card.warning .card-icon-container i {
  color: #E6A23C;
}

.card-data {
  flex: 1;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.card-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.card-change {
  font-size: 12px;
  display: flex;
  align-items: center;
}

.card-change.increase {
  color: #67C23A;
}

.card-change.decrease {
  color: #F56C6C;
}

.card-change i {
  margin-right: 3px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 100%;
  border-radius: 8px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.chart-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #409EFF;
  margin-right: 8px;
  border-radius: 2px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.rank-circle {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 12px;
  color: #606266;
}

.rank-circle.top-rank {
  background-color: #409EFF;
  color: white;
}

.product-info {
  display: flex;
  flex-direction: column;
}

.product-name {
  font-weight: 500;
  color: #303133;
}

.product-category {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.sales-value {
  font-weight: 600;
  color: #606266;
  margin-bottom: 5px;
  display: block;
}

.activity-row {
  margin-bottom: 20px;
}

.activity-card, .task-card {
  height: 100%;
  border-radius: 8px;
}

.activity-header, .task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.activity-title, .task-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.activity-title::before, .task-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #409EFF;
  margin-right: 8px;
  border-radius: 2px;
}

.timeline-content {
  padding: 5px 0;
}

.timeline-title {
  font-weight: 500;
  color: #303133;
}

.timeline-desc {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}

.task-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.task-item:last-child {
  border-bottom: none;
}

.task-completed {
  text-decoration: line-through;
  color: #c0c4cc;
}

.task-meta {
  display: flex;
  align-items: center;
}

.task-date {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}

::v-deep .el-card {
  border: none;
  overflow: visible;
}

::v-deep .el-card__header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

::v-deep .el-card__body {
  padding: 20px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
  display: flex;
  align-items: center;
}

.date-selector {
  display: flex;
  align-items: center;
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }
  
  .welcome-title {
    font-size: 20px;
  }
  
  .card-content {
    flex-direction: column;
    text-align: center;
  }
  
  .card-icon-container {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .chart-container {
    height: 250px;
  }
}
</style>
